
package com.xwyzsn.rentcar.service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xwyzsn.rentcar.entity.Comment;
import com.xwyzsn.rentcar.mapper.CommentMapper;
import com.xwyzsn.rentcar.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.lang.reflect.Field;
import java.util.Date;

@Service
public class CommentService  {

    @Autowired
    private CommentMapper commentMapper;
    public List<Comment> getOne(Map<String,?>payload){
        if (payload.isEmpty()){
            return commentMapper.getAll();
        }
        Integer id = (Integer) payload.get("id");
        return commentMapper.getOne(id);
    }

    public Boolean addOne(Map<String,?>payload){
        if (payload.isEmpty())return false;
        Comment comment = setEntity(payload,Comment.class);
        return commentMapper.addOne(comment);
    }

    public Boolean deleteOne(Map<String,?>payload){
        Integer id = (Integer) payload.get("id");
        return commentMapper.deleteOne(id);
    }

    public Integer updateOne(Map<String,?>payload){
        Comment comment = setEntity(payload,Comment.class);
        return commentMapper.updateOne(comment);
    }

    public static <T> T setEntity(Map<String, ?> payload, Class<T> clazz) {
        try {
            T entity = clazz.newInstance();
            Field[] fields = clazz.getDeclaredFields();

            for (Field field : fields) {
                String fieldName = field.getName();
                if (payload.containsKey(fieldName)) {
                    field.setAccessible(true);
                    Object value = payload.get(fieldName);

                    // Handle type conversions if necessary
                    if (field.getType() == Integer.class ) {
                        value = Integer.parseInt(String.valueOf(value));
                    } else if (field.getType() == Float.class ) {
                        value = Float.parseFloat(String.valueOf(value));
                    } else if (field.getType() == String.class){
                        value = String.valueOf(value);
                    }
                    field.set(entity, value);
                }
            }
            return entity;
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace(); // Handle or log the exception as needed
            return null;
        }
    }

    public Result getByUserId(Map<String, ?> payload) {
        Integer userId = Integer.parseInt(String.valueOf(payload.get("userId")));
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",userId);
        List<Comment> comments = commentMapper.selectList(queryWrapper);
        return Result.succ(comments);

    }
}

